package cn.lcl.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.log4j.Logger;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
/**
 * Jdbc连接数据库的工具，使用c3p0数据库连接池
 * Created by licho on 2017/8/15 0015.
 */
public class JdbcUtils {
    private  static  final Logger log=Logger.getLogger(JdbcUtils.class);
    private static  DataSource dataSource;
    private static ThreadLocal<Session> sessions=new ThreadLocal<>();//每个线程对应一个Sesson实例
    static {
        ComboPooledDataSource pool = new ComboPooledDataSource();//C3P0数据库连接池
        try {
            pool.setDriverClass(ProUtils.getProperty("jdbc.driver"));
            pool.setJdbcUrl(ProUtils.getProperty("jdbc.url"));
            pool.setUser(ProUtils.getProperty("jdbc.user"));
            pool.setPassword(ProUtils.getProperty("jdbc.pass"));
            dataSource=pool;
        } catch (PropertyVetoException e) {
            log.error("数据库连接池初始化失败",e);
        }
        log.info("数据库连接池初始化完成");
    }

    /**
     * 获取session
     * @return
     */
    public static Session getThreadSession(){
        Session s=sessions.get();
        if(s==null ||s.isClosed()){
            //如果该session已经关闭了。或者为null
            sessions.remove();
            sessions.set(buildSession());
        }
        return sessions.get();
    }
    public static void close(){
            Session s=sessions.get();
            if(!s.isClosed()){
                throw new RuntimeException("Session 未正常关闭");
            }
            sessions.remove();
        System.out.println("已经返回给线程池:"+(sessions.get()==null ?true :false));
    }

    /**
     * 创建一个新的Session对象
     * @return
     */
    private static Session buildSession(){
        Connection conn= null;//获取一个连接
        try {
            conn = dataSource.getConnection();
            Session s=new SessionImpl(conn);//创建session对象
            return  s;
        } catch (SQLException e) {
            log.error("创建Session对象失败");
            e.printStackTrace();
        }
        return null ;
    }
}
